var express = require('express');
var router = express.Router();
var PW = require('png-word');
var pw = new PW();
var random = require("random-js")();

var readJson = require('./readJson');
var path = require('path');
var filePath = path.join(__dirname,'..','public','liuyan.json');
var users = {};

function setValidateNum(req,res){
    req.session.firstnum = res.locals.firstnum = Math.round(Math.random()*10);
    req.session.secondnum = res.locals.secondnum = Math.round(Math.random()*10);
}
/* GET users listing. */
router.get('/login', function(req, res, next) {
    setValidateNum(req,res);
    res.render('login');
});

function checkValidateNum(req,res,next){
    if((req.session.firstnum+req.session.secondnum) === Number(req.body.vnum)){
        next();
    }else{
        next(new Error('验证码不正确!'));
    }
}

router.post('/login',checkValidateNum,(req,res,next)=>{
    const {username,password} = req.body;
    if(users[username]){
        if(users[username].password === password){
            res.locals.user = req.session.user = {username};
            readJson(filePath,function(dataString){
                res.render('index', { list : dataString ? JSON.parse(dataString).reverse() : [] });
            });
        }else{
            res.redirect('login');
        }
    }else{
        // setValidatePng(req,res);
        res.render('reg');
    }
});

router.get('/reg',function(req,res,next){
    res.render('reg');
});

router.post('/reg',function(req,res,next){
    const {username,password,confirm,vpng} = req.body;
    if(username && password && password === confirm && vpng == req.session.vpng){
        users[username] = {username,password};
        // res.redirect('/');
        res.locals.user = req.session.user || '';
        readJson(filePath,function(dataString){
             res.render('index', { list : dataString ? JSON.parse(dataString).reverse() : [] });
        });
    }else{
        res.render('reg');
    }
});

router.get('/vpng',function(req,res,next){
    req.session.vpng = random.integer(1000, 9999);
    pw.createReadStream(req.session.vpng+'').pipe(res);
});


router.get('/logout',(req,res,next)=>{
    res.locals.user = req.session.user = undefined;
    // res.render('index');
    readJson(filePath,function(dataString){
         res.render('index', { list : dataString ? JSON.parse(dataString).reverse() : [] });
    });
});

module.exports = router;
